<template>
  <div v-loading="loading">
    <search-head :search-data="searchData" @search="handleSearch" @reset="reset" />
    <ess-table
      ref="essTableRef"
      :other-container-box="otherContainerBox"
      :resize-observer-ele="resizeObserverEle"
      :thead-list="theadList"
      :page-num="searchData.pageNum"
      :total="total"
      :data-list="dataList"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selectionChange="selectionChange"
      @operationLog="operationLog"
    >
      <div v-if="hiddenNewProducts_Spu" slot="left" class="mune">
        <el-button size="mini" type="success" round @click="addSpu">单一新增</el-button>
      </div>
      <div slot="right" class="mune">
        <b>批量操作：</b>
        <el-upload v-show="false" ref="uploadTemplateRef" action="#" :auto-upload="false" :on-change="handleOnChange" />
        <el-button-group>
          <el-button v-if="hiddenNewProducts_Spu" size="mini" type="primary" round @click="uploadTemplate">批量新增</el-button>
          <el-button v-if="hiddenNewProducts_Spu" size="mini" type="primary" round :loading="btnLoading.export" @click="exportTemplate">下载模板</el-button>
          <el-button size="mini" type="primary" round :disabled="btnDisabled.submit" :loading="btnLoading.submit" @click="submit">提 交</el-button>
          <el-button size="mini" type="primary" round :disabled="btnDisabled.reject" :loading="btnLoading.reject" @click="reject"> 撤 回 </el-button>
          <el-button size="mini" type="primary" round :disabled="btnDisabled.abandon" @click="open('确定作废？', abandon, 50)"> 作 废 </el-button>
          <el-button
            size="mini"
            type="primary"
            round
            :disabled="btnDisabled.again"
            :loading="btnLoading.again"
            @click="open('确定更新到渠道？', textPushChannel, 50, false, 'id', true)"
          >
            推 送
          </el-button>
        </el-button-group>
      </div>
      <template v-slot:spuName="{ scope }">
        <span class="el-button--text el-button--mini" @click="verification(scope)">{{ scope.row.spuName }}</span>
      </template>
    </ess-table>
    <addSPU ref="addSPURef" :type="type" :menu-name="menuName" />
    <purchaseLog v-model="spulogVisible" width="900px" :title="title" :thead-list="spuOperationLogTableHeader" :data-list="operationLogTableList" />
  </div>
</template>

<script>
import searchHead from '../components/searchHead.vue'
import essTable from '@/components/eTable/eTable.vue'
import purchaseLog from '@/components/dialogTableInfo/dialogTableInfo.vue'
import { withdraw, exportTemplate as exportTemplateApi, uploadTemplate as uploadTemplateApi } from '@/api/coi/onlineTaskAPI/spu.js'
import { spuListHeader } from '@/views/coi/commonJs/tableHeadList.js'
import { pushFun, spuOperationLog, abandonFun } from '../js/maintain.js'
import { checkBoxFun } from '@/views/coi/commonJs/publicMethod.js'
import moment from 'moment'
import { stringToArray } from '@/utils/processingData'
import addSPU from '../components/addSPU'
import bus from '@/utils/eventBus.js'
// import eventBus from '@/utils/eventBus'

export default {
  name: 'List',
  components: {
    searchHead,
    essTable,
    addSPU,
    purchaseLog
  },
  mixins: [checkBoxFun, pushFun, spuOperationLog, abandonFun],
  props: {
    getListFun: {
      type: Function,
      required: true
    },
    submitFun: {
      type: Function,
      required: true
    },
    type: {
      type: String,
      default: ''
    },
    menuName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      theadList: spuListHeader,
      otherContainerBox: ['.app-container', '.checkComponent'],
      resizeObserverEle: ['.app-main', '.app-container'],
      searchData: {},
      total: 0,
      dataList: [],
      multipleSelection: [],
      btnDisabled: {
        submit: true,
        reject: true,
        again: true,
        abandon: true
      },
      btnLoading: {
        submit: false,
        reject: false,
        again: false,
        export: false
      },
      routeName: this.$route.name,
      hiddenNewProducts_Spu: !window.appConfig.hiddenNewProducts_Spu
    }
  },
  watch: {
    multipleSelection: {
      deep: true,
      handler(val) {
        if (Array.isArray(val) && val.length !== 0) {
          this.btnDisabled.submit = !val.every((item) => item.mainStatus === 201)
          this.btnDisabled.reject = !val.every((item) => item.mainStatus === 301 || item.mainStatus === 403 || item.mainStatus === 401)
          this.btnDisabled.again = !val.every((item) => item.mainStatus === 401 || item.mainStatus === 403)
          this.btnDisabled.abandon = !val.every((item) => item.mainStatus !== 998 && item.mainStatus !== 999)
        } else {
          this.btnDisabled.submit = true
          this.btnDisabled.reject = true
          this.btnDisabled.again = true
          this.btnDisabled.abandon = true
        }
      }
    }
  },
  created() {
    this.initalData()
    this.queryData()
  },
  activated() {
    this.handleSearch()
  },
  methods: {
    initalData() {
      const searchData = {
        pageNum: 1,
        pageSize: 10
      }
      this.searchData = searchData
    },
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if ('skuList' in searchData) searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/)
      return searchData
    },
    // 分页器
    handleCurrentChange(val) {
      this.searchData.pageNum = val
      this.queryData()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    async queryData() {
      try {
        this.loading = true
        const { result } = await this.getListFun(this.handleData())
        if (!result) return
        if (Array.isArray(result.list)) {
          result.list.forEach((e) => {
            if (e.updateTime) e.updateTime = moment(e.updateTime).format('YYYY-MM-DD HH:mm:ss')
          })
        }
        this.total = result.total || 0
        this.dataList = result.list || []
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.$refs.essTableRef && this.$refs.essTableRef.clearSelection()
      this.handleCurrentChange(1)
    },
    reset() {
      this.initalData()
      this.handleSearch()
    },
    addSpu() {
      this.$refs.addSPURef.dialogVisible = true
    },
    // 校验批量数据
    checkQuantity(val, maxNum = 500) {
      const arr = val && Array.isArray(val) && val.length ? val : false
      const multipleSelection = arr || this.multipleSelection
      if (multipleSelection.length > maxNum) {
        this.$message({
          type: 'warning',
          message: `批量任务数量不能超过${maxNum}条`
        })
        return false
      } else return multipleSelection
    },
    confim(message = '', callBack) {
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (callBack) callBack()
        })
        .catch(() => {})
    },
    submit() {
      const dataList = this.checkQuantity([], 50)
      if (!dataList && Array.isArray(dataList)) return
      const idList = dataList.map((_) => _.id)
      this.confim('确认提交？', () => {
        this.submitRequery(idList)
      })
    },
    async submitRequery(idList) {
      try {
        this.btnLoading.submit = true
        const { code, result } = await this.submitFun(idList)
        if (code !== '0') return
        this.$message({
          type: 'success',
          message: result || '提交成功！'
        })
        this.handleSearch()
      } finally {
        this.btnLoading.submit = false
      }
    },
    reject() {
      const dataList = this.checkQuantity([], 50)
      if (!dataList && Array.isArray(dataList)) return
      const idList = dataList.map((_) => _.id)
      this.confim('确认撤回？', () => {
        this.rejectRequery(idList)
      })
    },
    async rejectRequery(idList) {
      try {
        this.btnLoading.reject = true
        const { code, result: message } = await withdraw(idList)
        if (code !== '0') return
        this.handleSearch()
        if (!message) return
        this.$message({
          type: 'success',
          message
        })
      } finally {
        this.btnLoading.reject = false
      }
    },
    verification({ row }) {
      // console.log('row', row)
      // return
      const mainStatus = row.mainStatus
      if (!mainStatus) return
      const id = row.id
      if (mainStatus === 101 || mainStatus === 102) {
        this.$refs.addSPURef.dialogVisible = true
        this.$refs.addSPURef.formData.spuId = id
        this.$refs.addSPURef.verificationInfo()
      } else {
        bus.$emit('setTagName', row.spuName)
        console.log('row', row.spuName)
        const query = {}
        // 判断渠道 跳转不同的编辑页面
        if (this.menuName) {
          query.menuName = this.menuName
        }
        let url = `/spuSeries/${id}/${mainStatus}/${this.$route.name}`
        if (row.channelType && Number(row.channelType) === 12) {
          const statusList = [101, 301, 401, 403, 999, 998]
          const mainStatus = row.mainStatus
          // const {rolesTable} = this.$store.state.user
          // console.log('rolesTable', rolesTable)
          // return
          if (statusList.includes(mainStatus)) query.disabled = 'disabled'
          if (mainStatus === 301) {
            const { rolesTable } = this.$store.state.user
            const code = 'R017012'
            if (rolesTable.includes(code)) query.disabled = 'disabled'
          }
          query.status = 'edit'
          query.id = row.id
          const disabled = query.disabled ? query.disabled : query.status
          query.menuName = this.menuName
          // this.$router.meta.title = row.spuName
          url = `/addspu/${row.id}/${disabled}`
          // bus.$emit('setTagName', row.spuName)
        }
        this.$router.push({
          path: url,
          query
        })
      }
    },
    async exportTemplate() {
      try {
        this.btnLoading.export = true
        await exportTemplateApi()
      } finally {
        this.btnLoading.export = false
      }
    },
    uploadTemplate() {
      this.$refs.uploadTemplateRef &&
        this.$refs.uploadTemplateRef.$refs['upload-inner'] &&
        this.$refs.uploadTemplateRef.$refs['upload-inner'].handleClick &&
        this.$refs.uploadTemplateRef.$refs['upload-inner'].handleClick()
    },
    async handleOnChange({ raw }) {
      try {
        const date = moment(new Date()).format('YYYY-MM-DD')
        this.loading = true
        const formData = new FormData()
        formData.append('file', raw)
        const res = await uploadTemplateApi(formData, `批量新增spu异常数据 - ${date}`)
        console.log(res)
        if (res && res.code === '0') {
          this.$message({
            message: '批量新增spu上传成功！',
            type: 'success'
          })
        } else {
          this.$message({
            message: '批量新增spu数据存在异常，详情见文档！',
            type: 'error'
          })
        }
      } finally {
        this.loading = false
        this.handleSearch()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.mune {
  padding-bottom: 8px;
}
</style>
